package cn.com.hbhgkj.webapp.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;

import com.google.code.kaptcha.Constants;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;

/**
 * Filter to wrap request with a request including user preferred locale.
 */
public class CaptchaValidateFilter implements Filter {
	private FilterConfig config;
	
	private Map<String,String> inputMappings = new HashMap<String,String>();

	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		String captcha = request.getParameter("captcha");

		HttpSession session = req.getSession(false);

		Object storedCaptcha = session
				.getAttribute(Constants.KAPTCHA_SESSION_KEY);

		if (StringUtils.isEmpty(captcha) || !captcha.equals(storedCaptcha)){
			String resURI;
			
			if(req.getContextPath().equals("")){
				resURI = req.getRequestURI();
			}else{
				resURI = req.getRequestURI().substring(req.getRequestURI().lastIndexOf("/"));
			}
			
			
			//System.out.println("valuestack " + ServletActionContext.getValueStack(req));
			//req.setAttribute("captchaInvalid", true);
			
			//req.getRequestDispatcher("/signup").forward(req, response);
			resp.sendRedirect(inputMappings.get(resURI) + "?captchaInvalid=true");
			//resp.sendRedirect(inputMappings.get(req.getRequestURI()));
			
		}

		chain.doFilter(request, response);
	}
	
	public void init(FilterConfig config) throws ServletException {
		this.config = config;
		//j_security_check:login,saveSignup:signup
		String[] mappings = this.config.getInitParameter("inputMapping").split(",");
		for(String each : mappings){
			String[] entries = each.split(":");
			inputMappings.put(entries[0], entries[1]);
		}
		
	}
	
	@Override
	public void destroy() {
		this.config = null;
	}

}
